package com.ncloud.auth.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ncloud.auth.config.RedisItem;
@Component
public class LocalTokenService{

	@Autowired
	public RedisTemplate<String, String> redisTemplate;
	public byte[] get(RedisItem item) {
		return redisTemplate.execute(new RedisCallback<byte []>() {
			@Override
			public byte []  doInRedis(RedisConnection redisConnection) throws DataAccessException {
				return redisConnection.get(item.getKey().getBytes());
			}
		});
	}
	public void set(List<RedisItem> list) {
		redisTemplate.execute(new RedisCallback<byte[]>() {
			@Override
			public byte[] doInRedis(RedisConnection redisConnection) throws DataAccessException {
				for(RedisItem item : list){
					byte[] key = item.getKey().getBytes();
					byte[] value = JSON.toJSONBytes(item.getValue());
					redisConnection.set(key, value);
					redisConnection.expire(key, item.getExpire());
				}
				return null;
			}
		});
	}
	public void expire(List<RedisItem> list) {
		redisTemplate.execute(new RedisCallback<byte[]>() {
			@Override
			public byte[] doInRedis(RedisConnection redisConnection) throws DataAccessException {
				for(RedisItem item : list){
					byte[] key = item.getKey().getBytes();
					redisConnection.expire(key, item.getExpire());
				}
				return null;
			}
		});
	}
	public void delete(String [] deleteKeys) {
		redisTemplate.execute(new RedisCallback<byte[]>() {
			@Override
			public byte[] doInRedis(RedisConnection redisConnection) throws DataAccessException {
				for(String string : deleteKeys){
					byte[] key = string.getBytes();
					redisConnection.del(key);
				}
				return null;
			}
		});
	}	
}
